import CartoonImage from '../../assets/cartoon.jpg';
import FoodImage from '../../assets/food.jpg';
import MovieImage from '../../assets/movie.png';
import LiftImage from '../../assets/life.jpg';
import styles from './index.module.scss';
import { useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import LogoImage from '../../assets/logo.png';

type Tab = {
  id: string;
  titie: string;
  image: string;
};

const SecondSection: React.FC = () => {
  const [activeTab, setActiveTab] = useState<string>('cartoon');
  const secondSectionRef = useRef<HTMLDivElement>(null);
  const [isFixed, setIsFixed] = useState(false);

  const tabList: Tab[] = [
    {
      id: 'cartoon',
      titie: '动画',
      image: CartoonImage,
    },
    {
      id: 'food',
      titie: '美食',
      image: FoodImage,
    },
    {
      id: 'movie',
      titie: '电影',
      image: MovieImage,
    },
    {
      id: 'life',
      titie: '生活',
      image: LiftImage,
    },
  ];

  const activate = (id: string) => {
    setActiveTab(id);
    const tabContentEl = document.querySelector(`[data-id=${id}]`);
    tabContentEl && tabContentEl.scrollIntoView({ behavior: 'smooth' });
  };

  const onScroll = () => {
    if (secondSectionRef.current) {
      const { top } = secondSectionRef.current.getBoundingClientRect();
      setIsFixed(top <= 0);

      const sectionNodes = secondSectionRef.current.querySelectorAll(
        'section'
      ) as NodeListOf<HTMLElement>;
      Array.from(sectionNodes).forEach(sectionEl => {
        const { top } = sectionEl.getBoundingClientRect();
        const id = sectionEl.getAttribute('data-id') as string;
        top <= 56 && setActiveTab(id);
      });
    }
  };

  useEffect(() => {
    document.addEventListener('scroll', onScroll);

    return () => {
      document.removeEventListener('scroll', onScroll);
    };
  }, []);

  return (
    <div className={classNames(styles.secondSection, { fixed: isFixed })} ref={secondSectionRef}>
      <div>
        <ul className={classNames({ fixed: isFixed })}>
          {tabList.map(item => {
            return (
              <li
                key={item.id}
                className={item.id === activeTab ? 'active' : ''}
                onClick={() => activate(item.id)}
              >
                {item.titie}
              </li>
            );
          })}
        </ul>
      </div>

      <div>
        {tabList.map(item => {
          return (
            <section key={item.id} data-id={item.id}>
              <h2>{item.titie}</h2>
              <img src={item.image} alt={item.id + `img`} />
            </section>
          );
        })}
      </div>

      {/* 吸顶按钮 */}
      <div className={classNames('btnWrapper', { fixed: isFixed })}>
        <img src={LogoImage} alt="logo img" />
        <button>App 内打开</button>
      </div>
    </div>
  );
};

export default SecondSection;
